<?php
class Authentication extends W4eObject{
    /**
    * Login method
    * Input: Username = Username for login
    *       Password =   Password for login
    *       Section =  Admin or User (ADMIN = 1; END_USER = 0)
    *       URL ERROR   =   URL if ERROR
    */
    
    function login($username, $password){
        global $cfg_session_live_time, $cfg_session_timeout;
        if (empty($username) || empty($password)){
            return EMPTY_USER_PWD;
        }else{       
        	$baseDAO = new BaseDAO();
            $user = $baseDAO->getItem("user", array("id", "username", "fullname", "email", "password", "status", "isuser"), $username, "username");
            if (!$user){                                
                return WRONG_USER_PWD;     
            }else if(sha1($password) != $user["password"]){     
                return WRONG_USER_PWD;
            }else if($user["status"] < 1){
            	return NOT_ACTIVIATED;
            }else{
                /**
                * Authenticate success. Register session variable
                */
                //Get access control list of current user   
                //Session::create();
                Session::setExpire($cfg_session_live_time);
                Session::set('isuser', $user['isuser']);
                Session::set('userid', $user["id"]);
                Session::set('username', $username);
                Session::set('fullname', $user["fullname"]);
                Session::set('Authenticate_RemoteAddr', $_SERVER['REMOTE_ADDR']);
                Session::set('Authenticate_UserAgent', $_SERVER['HTTP_USER_AGENT']);

                //Session::setIdle($cfg_session_timeout);
                //Update last visit of user
//                UserDAO::setLastVisit($username);
                //Delete all sessions of this user
                //Update session

                return LOGIN_SUCC;
            }
        }
    }

    function logout(){
        Session::destroy();
    }

    function isAuthenticated(){                
        /*
        if (Session::isExpired()){  
            //die("here"           );
           return SESSION_TIMEOUT;
        } 
        */       

        if (Session::get('guest') != 0 || Session::get('username') == null){            
            
            return NOT_LOGON;
        }
                
        
        return AUTHED_SUCC;
    }


    function generateRandomPassword($length = 8){
        $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $len = strlen($salt);
        $makepass = "";
        mt_srand(10000000 * (double) microtime());

        for($i = 0; $i < $length; $i++){
            $makepass .= $salt[mt_rand(0, $len -1)];
        }
        return $makepass;
    }
    
   
}
?>